package com.example.view.custom;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Scroller;

public class MySlideView extends ViewGroup {

    private Context mContext;
    private View mMenu;
    private View mContent;
    private int firstX;
    private int lastX;
    private boolean isMenuShow;
    private Scroller scroller;

    public MySlideView(Context context) {
        super(context);
    }

    public MySlideView(Context context, AttributeSet attrs) {
        super(context, attrs);
        this.mContext = context;
        scroller = new Scroller(context);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mMenu = getChildAt(0);
        mContent = getChildAt(1);

        mMenu.measure(MeasureSpec.makeMeasureSpec(mMenu.getLayoutParams().width, MeasureSpec.EXACTLY), heightMeasureSpec);
        mContent.measure(widthMeasureSpec, heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mMenu.layout(0 - mMenu.getMeasuredWidth(), 0, 0, b);
        mContent.layout(0, 0, r, b);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                firstX = lastX = (int) event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                int disX = (int) (lastX - event.getX());
                lastX = (int) event.getX();
                int nextScrollX = getScrollX() + disX;      //
                if (nextScrollX >= -mMenu.getWidth() && nextScrollX <= 0) {
                    scrollBy(disX, 0);
                }
                break;

            case MotionEvent.ACTION_UP:
                int curScrollX = getScrollX();
                if (curScrollX > -mMenu.getWidth() / 2) {
                    isMenuShow = false;
                } else {
                    isMenuShow = true;
                }
                flushState();
                break;
        }

        return true;
    }

    private void flushState() {
        int distance = 0;
        if (!isMenuShow) {
            //scrollTo(0,0);
            distance = 0 - getScrollX();
        } else {
            //scrollTo(-mMenu.getWidth(),0);
            distance = -mMenu.getWidth() - getScrollX();
        }

        scroller.startScroll(getScrollX(), 0, distance, 0);
        invalidate();
    }

    public void changeState() {
        isMenuShow = !isMenuShow;
        flushState();
    }
}
